package com.thh.create;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.index.reindex.DeleteByQueryRequestBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;

/**
 * 演示ES的Document的删除
 */
public class App04_DeleteDocument {

    //定义客户端
    TransportClient client;

    /*
    删除对象
     */
    @Test
    public void test1() throws Exception  {

        //删除文档
        client.prepareDelete("xiaofeifei_index","book","7").get();

    }










    /**
     * 不推荐：有可能删除错数据
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {

        //1.构建删除条件（链式写法）
       /* BulkByScrollResponse response = DeleteByQueryAction.INSTANCE
                .newRequestBuilder(client)
                .filter(QueryBuilders.termsQuery("bookname", "java")) //QueryBuilders.termsQuery(): 根据词条来进行查询
                .source("xiaofeifei_index")  // source("")：需要操作的索引
                .get();*/

        //非链式写法
        DeleteByQueryRequestBuilder builder = DeleteByQueryAction.INSTANCE.newRequestBuilder(client);
        builder = builder.filter(QueryBuilders.termsQuery("bookname", "java"));
        builder = builder.source("xiaofeifei_index");
        BulkByScrollResponse response = builder.get();

        //2.返回删除的记录数
        long deleteCount = response.getDeleted();
        System.out.println("一共删除了"+deleteCount+"条");

    }



    //初始化
    @Before
    public void init() throws Exception {
        //1、创建一个Settings对象，相当于一个配置信息。主要配置集群的名称。 cluster.name配置集群名称
        Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
        //2、创建一个客户端client对象。
        client = new PreBuiltTransportClient(settings);
        //3、使用client对象创建一个索引库。
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9300));
    }

    //释放资源
    @After
    public void close(){
        //4、关闭client对象。
        client.close();
    }
}
